<?php
session_start();
require_once '../config/database.php';
require_once '../includes/functions.php';

header('Content-Type: application/json');

// 检查用户登录状态
$is_logged_in = isset($_SESSION['user_id']);
$user_id = $is_logged_in ? $_SESSION['user_id'] : null;

try {
    // 更新游戏状态
    updateGameState();
    
    // 获取基本游戏数据（无论是否登录都可以获取）
    $current_round = getCurrentRound();
    $current_price = getCurrentPrice();
    $price_history = getPriceHistory(50);
    
    // 获取用户相关数据（仅登录用户）
    $user_balance = $is_logged_in ? getUserBalance($user_id) : 0;
    $user_frozen_profit = $is_logged_in ? getUserFrozenProfit($user_id) : 0;
    $user_positions = $is_logged_in ? getUserPositions($user_id) : [];
    
    // 计算轮次状态
    $now = time();
    $round_start = strtotime($current_round['start_time']);
    $trading_end = $round_start + (10 * 60); // 10分钟交易时间
    $round_end = strtotime($current_round['end_time']);
    
    $status_text = '';
    if ($now <= $trading_end) {
        $status_text = '交易中';
    } elseif ($now <= $round_end) {
        $status_text = '休市中';
    } else {
        $status_text = '准备下一轮';
    }
    
    $response = [
        'success' => true,
        'is_logged_in' => $is_logged_in,
        'current_price' => $current_price,
        'price_history' => $price_history,
        'round_info' => [
            'round_number' => $current_round['round_number'],
            'status' => $current_round['status'],
            'status_text' => $status_text,
            'start_time' => $current_round['start_time'],
            'end_time' => $current_round['end_time']
        ],
        'user_balance' => $user_balance,
        'user_frozen_profit' => $user_frozen_profit,
        'positions' => $user_positions
    ];
    
    echo json_encode($response);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => '更新失败: ' . $e->getMessage()
    ]);
}
?>
